package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.GradeCustomRuleYearClass;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级自定义设置 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-28
 */
@RestController
@RequestMapping("/api/gradeCustomSet")
public class GradeCustomSetController extends  BaseController{

    @Autowired
    IGradeCustomSetService iGradeCustomSetService;
    @Autowired
    IGradeCustomGradeService iGradeCustomGradeService;
    @Autowired
    IGradeCustomRuleCountService iGradeCustomRuleCountService;
    @Autowired
    IGradeCustomRuleWeeksService iGradeCustomRuleWeeksService;
    @Autowired
    IGradeCustomRuleTimesService iGradeCustomRuleTimesService;


    @PostMapping("/saveGradeCustomSet")
    public Result saveGradeCustomSet(@RequestBody GradeCustomSet gradeCustomSet){

        gradeCustomSet.setCreatedId(this.adminId);
        boolean save = iGradeCustomSetService.saveGradeCustomSet(gradeCustomSet);
        if (save){
            return new Result(Code.OK,"","保存成功");
        }else {
            return new Result(Code.ERROR,"","保存失败");
        }
    }

    @PostMapping("/isExistStudent")
    public Result isExistStudent(@RequestBody Map reMap){
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()) {
            return new Result(Code.ERROR, "", "未提供有效的ID列表");
        }
        StringBuilder errorMessage = new StringBuilder();

        for (String id : ids) {
            GradeCustomGrade gradeCustomGrade = iGradeCustomGradeService.getById(id);
            if (gradeCustomGrade == null) {
                return new Result(Code.ERROR, "", "ID为 " + id + " 的数据不存在");
            }

            String weekDates = null;
            String week = null;

            String schedulingType = gradeCustomGrade.getSchedulingType();
            if ("A类".equals(schedulingType)) {
                weekDates = "1,2,3,4,5";
                week = "周内";
            } else if ("B类".equals(schedulingType)) {
                weekDates = "6,0";
                week = "周末";
            }

            QueryWrapper<GradeCustomSet> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", gradeCustomGrade.getGradeCustomSetId());
            queryWrapper.eq("deleted", 0);
            queryWrapper.last("limit 1");
            GradeCustomSet gradeCustomSet = iGradeCustomSetService.getOne(queryWrapper);

            if (gradeCustomSet == null) {
                return new Result(Code.ERROR, "", "ID为 " + id + " 的数据不存在");
            }
            String lessonType = String.valueOf(gradeCustomSet.getLessonType());
            String quarterNum = String.valueOf(gradeCustomSet.getQuarterNum());
            String yearPart = String.valueOf(gradeCustomSet.getYearPart());
            String schoolId = String.valueOf(gradeCustomSet.getSchoolId());
            String subjectsId = String.valueOf(gradeCustomSet.getSubjectsId());
            String timeStart = gradeCustomGrade.getTimeStart();
            String timeEnd = gradeCustomGrade.getTimeEnd();

            List<String> names = iGradeCustomSetService.getStudentGradeName(yearPart, quarterNum, lessonType, schoolId, subjectsId, weekDates, timeStart, timeEnd, schedulingType);
            if (!names.isEmpty()) {
                errorMessage.append(week).append(" ").append(timeStart).append(" - ").append(timeEnd).append(" 时间段，班级 ");
                errorMessage.append(String.join(", ", names)).append(" 已有学生，无法操作；");
            }
        }
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("count",errorMessage.length());
        return new Result(Code.OK, objectMap, errorMessage.toString().trim());
    }


    @GetMapping("/getGradeCustomSetDetails")
    public Result getGradeCustomSetDetails(@RequestParam(value = "yearPart", defaultValue = "", required = true) String yearPart,
                                           @RequestParam(value = "quarterNum", defaultValue = "", required = true) String quarterNum,
                                           @RequestParam(value = "lessonType", defaultValue = "", required = true) String lessonType,
                                           @RequestParam(value = "schoolId", defaultValue = "", required = true) String schoolId,
                                           @RequestParam(value = "subjectsId", defaultValue = "", required = true) String subjectsId){
        QueryWrapper<GradeCustomSet>  queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("school_id",schoolId);
        queryWrapper.eq("lesson_type",lessonType);
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("quarter_num",quarterNum);
        queryWrapper.eq("subjects_id",subjectsId);
        queryWrapper.eq("deleted",0);
        queryWrapper.last("limit 1");
        GradeCustomSet gradeCustomSet = iGradeCustomSetService.getOne(queryWrapper);
        if (gradeCustomSet!=null){
            QueryWrapper<GradeCustomGrade> customGradeQueryWrapper = new QueryWrapper<>();
            customGradeQueryWrapper.eq("grade_custom_set_id",gradeCustomSet.getId());
            customGradeQueryWrapper.eq("deleted",0);
            List<GradeCustomGrade> gradeCustomGradeList = iGradeCustomGradeService.list(customGradeQueryWrapper);
            gradeCustomSet.setGradeCustomGradeList(gradeCustomGradeList);

            // 查询 gradeCustomRuleCountList
            QueryWrapper<GradeCustomRuleCount> ruleCountQueryWrapper = new QueryWrapper<>();
            ruleCountQueryWrapper.eq("grade_custom_set_id", gradeCustomSet.getId());
            ruleCountQueryWrapper.eq("deleted", 0);
            List<GradeCustomRuleCount> gradeCustomRuleCountList = iGradeCustomRuleCountService.list(ruleCountQueryWrapper);
            // 查询 gradeCustomRuleTimesList
            QueryWrapper<GradeCustomRuleTimes> ruleTimesQueryWrapper = new QueryWrapper<>();
            ruleTimesQueryWrapper.eq("grade_custom_set_id", gradeCustomSet.getId());
            ruleTimesQueryWrapper.eq("deleted", 0);
            List<GradeCustomRuleTimes> gradeCustomRuleTimesList = iGradeCustomRuleTimesService.list(ruleTimesQueryWrapper);
            // 查询 gradeCustomRuleWeeksList
            QueryWrapper<GradeCustomRuleWeeks> ruleWeeksQueryWrapper = new QueryWrapper<>();
            ruleWeeksQueryWrapper.eq("grade_custom_set_id", gradeCustomSet.getId());
            ruleWeeksQueryWrapper.eq("deleted", 0);
            List<GradeCustomRuleWeeks> gradeCustomRuleWeeksList = iGradeCustomRuleWeeksService.list(ruleWeeksQueryWrapper);


            // 分组数据
            Map<Integer, List<GradeCustomRuleCount>> ruleCountMap = gradeCustomRuleCountList.stream()
                    .collect(Collectors.groupingBy(GradeCustomRuleCount::getYearClassId));
            Map<Integer, List<GradeCustomRuleTimes>> ruleTimesMap = gradeCustomRuleTimesList.stream()
                    .collect(Collectors.groupingBy(GradeCustomRuleTimes::getYearClassId));
            Map<Integer, List<GradeCustomRuleWeeks>> ruleWeeksMap = gradeCustomRuleWeeksList.stream()
                    .collect(Collectors.groupingBy(GradeCustomRuleWeeks::getYearClassId));

            // 初始化 customRuleYearClassList
            List<GradeCustomRuleYearClass> customRuleYearClassList = new ArrayList<>();

            // 获取所有 yearClassId
            Set<Integer> yearClassIds = new HashSet<>();
            yearClassIds.addAll(ruleCountMap.keySet());
            yearClassIds.addAll(ruleTimesMap.keySet());
            yearClassIds.addAll(ruleWeeksMap.keySet());

            for (Integer yearClassId : yearClassIds) {
                GradeCustomRuleYearClass gradeCustomRuleYearClass = new GradeCustomRuleYearClass();
                gradeCustomRuleYearClass.setYearClassId(yearClassId);
                gradeCustomRuleYearClass.setGradeCustomRuleCountList(ruleCountMap.getOrDefault(yearClassId, new ArrayList<>()));
                gradeCustomRuleYearClass.setGradeCustomRuleTimesList(ruleTimesMap.getOrDefault(yearClassId, new ArrayList<>()));
                gradeCustomRuleYearClass.setGradeCustomRuleWeeksList(ruleWeeksMap.getOrDefault(yearClassId, new ArrayList<>()));
                customRuleYearClassList.add(gradeCustomRuleYearClass);
            }

            // 设置 customRuleYearClassList 到 gradeCustomSet
            gradeCustomSet.setCustomRuleYearClassList(customRuleYearClassList);

        }

        return new Result(Code.OK,gradeCustomSet,"查询成功");

    }


}
